package com.exception;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

/**
 * TestException.java
 * @author  microxdd
 * @version 创建时间：2014 2014年9月16日 上午12:29:46 
 * micrxdd
 * 
 */
public class TestException extends SimpleMappingExceptionResolver{

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
	    HttpServletResponse response, Object handler, Exception ex) {
	// TODO Auto-generated method stub
	if (handler != null) {
	    HandlerMethod handlerMethod = (HandlerMethod) handler;
	    Method method = handlerMethod.getMethod();
	    System.out.println("method:"+method);
	    ex.printStackTrace();
	    if (method != null) {
		ModelAndView mav=new ModelAndView();
		ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(
			method, ResponseBody.class);
		if (responseBodyAnn != null) {
		    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		    MappingJacksonJsonView view = new MappingJacksonJsonView();
		    Map<String, Object> attributes = new HashMap<String, Object>();
		    attributes.put("success", Boolean.FALSE);
		    attributes.put("msg", ex.toString());
		    view.setAttributesMap(attributes);
		    mav.setView(view);
		    //mav.addObject(attributes);
		    System.out.println("============exception================");
		    return mav;
		}
	    }
	}
	return super.doResolveException(request, response, handler, ex);
    }

}
